{% extends "base.html" %}

{% block title %}依赖项管理{% endblock %}

{% block content %}
<style>
.package-form-row {
    display: flex;
    align-items: flex-end;
    gap: 15px;
}

.package-form-row .form-group {
    flex: 1;
    margin-bottom: 0;
}

.package-form-row .form-group label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    color: #495057;
}

.package-form-row .form-group .form-control,
.package-form-row .form-group .btn {
    width: 100%;
    height: 38px;
}

/* 镜像源下拉框特殊样式 */
.package-form-row .form-group select#mirrorSource {
    font-size: 12px;
    padding: 6px 8px;
}

.package-form-row .form-group select#mirrorSource option {
    font-size: 12px;
    padding: 4px 8px;
}

.package-form-row .form-group small {
    display: block;
    margin-top: 4px;
    font-size: 12px;
    color: #6c757d;
    line-height: 1.2;
    min-height: 14px;
}

.package-form-row .form-group:not(:has(small)) {
    padding-bottom: 18px;
}

.package-form-row .form-group:has(small) {
    padding-bottom: 0;
}

/* 确保所有输入框和按钮高度一致 */
.package-form-row .form-control,
.package-form-row .btn {
    box-sizing: border-box;
    border: 1px solid #ced4da;
    border-radius: 0.375rem;
    font-size: 14px;
    line-height: 1.5;
}

.package-form-row .form-control:focus,
.package-form-row .btn:focus {
    border-color: #86b7fe;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
    outline: 0;
}

/* 液态玻璃风格补充 */
.glass-card {
    background: rgba(255,255,255,0.6) !important;
    backdrop-filter: blur(16px) !important;
    -webkit-backdrop-filter: blur(16px) !important;
    border: 1px solid rgba(255,255,255,0.2) !important;
    border-radius: 1rem !important;
    box-shadow: 0 8px 32px 0 rgba(31,38,135,0.10) !important;
    transition: all 0.3s cubic-bezier(0.4,0,0.2,1) !important;
}
.glass-card .card-header, .glass-card .card-body {
    background: transparent !important;
}
[data-theme="dark"] .glass-card {
    background: rgba(30,30,30,0.7) !important;
    border-color: rgba(255,255,255,0.1) !important;
}

/* 液态玻璃风格补充 */
.page-title-glass {
    color: #222 !important;
    transition: color 0.2s;
}
[data-theme="dark"] .page-title-glass {
    color: #fff !important;
}

/* 紧凑的操作按钮组样式 */
.compact-btn-group {
    display: flex;
    gap: 2px;
    flex-wrap: nowrap;
}

.compact-btn-group .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    line-height: 1.2;
    border-radius: 0.25rem;
    min-width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.compact-btn-group .btn i {
    font-size: 0.7rem;
}

/* 操作列最小宽度 */
.table th:last-child,
.table td:last-child {
    min-width: 80px;
    max-width: 100px;
    white-space: nowrap;
}

/* 确保表格响应式 */
.table-responsive {
    overflow-x: auto;
}

/* 优化表格列宽 */
#packagesTable th:nth-child(1) { min-width: 120px; } /* 包名 */
#packagesTable th:nth-child(2) { min-width: 80px; }  /* 版本 */
#packagesTable th:nth-child(3) { min-width: 200px; } /* 描述 */
#packagesTable th:nth-child(4) { min-width: 150px; } /* 位置 */
#packagesTable th:nth-child(5) { min-width: 80px; }  /* 类型 */
#packagesTable th:nth-child(6) { min-width: 80px; }  /* 操作 */
</style>
<div class="container-fluid">
    <!-- 页面标题 -->
    <div class="glass-card mb-4 p-3 d-flex justify-content-between align-items-center">
        <h1 class="h3 mb-0 page-title-glass">
            <i class="fas fa-boxes mr-2"></i>依赖项管理
        </h1>
        <div>
            <!-- 后台安装功能已移除 -->
            <a href="{{ url_for('package_logs') }}" class="btn btn-info">
                <i class="fas fa-history mr-1"></i>操作日志
            </a>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="glass-card card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                总包数量
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800 total-packages">{{ total_packages }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-boxes fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="glass-card card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                用户包数量
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800 user-packages">{{ user_packages_count }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-user fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="glass-card card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                核心包数量
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800 core-packages">{{ core_packages_count }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-shield-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="glass-card card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                本周操作次数
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ recent_operations }}</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-tools fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 操作面板 -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="glass-card card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">包管理操作</h6>
                </div>
                <div class="card-body">
                    <form id="installForm">
                        <div class="package-form-row">
                            <div class="form-group" style="flex: 2;">
                                <label for="installPackageName">包名</label>
                                <input type="text" class="form-control" id="installPackageName" 
                                       placeholder="例如: requests" required>
                            </div>
                            <div class="form-group" style="flex: 1.5;">
                                <label for="installVersion">版本（可选）</label>
                                <input type="text" class="form-control" id="installVersion" 
                                       placeholder="例如: 2.28.1">
                                <small class="form-text text-muted">建议指定版本号</small>
                            </div>
                            <div class="form-group" style="flex: 2.5;">
                                <label for="mirrorSource">镜像源</label>
                                <select class="form-control" id="mirrorSource">
                                    <option value="官方源">官方源</option>
                                    <option value="清华大学">清华</option>
                                    <option value="阿里云">阿里云</option>
                                    <option value="中国科技大学">中科大</option>
                                    <option value="豆瓣">豆瓣</option>
                                    <option value="华为云">华为云</option>
                                    <option value="腾讯云">腾讯云</option>
                                </select>
                                <small class="form-text text-muted">选择镜像源加快下载</small>
                            </div>
                            <div class="form-group" style="flex: 1;">
                                <label>&nbsp;</label>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-download mr-1"></i>安装
                                </button>
                            </div>
                            <div class="form-group" style="flex: 1;">
                                <label>&nbsp;</label>
                                <button type="button" class="btn btn-secondary" onclick="refreshPackages()">
                                    <i class="fas fa-sync-alt mr-1"></i>刷新
                                </button>
                            </div>
                            <!-- 后台安装功能已移除 -->
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 已安装包列表 -->
    <div class="row">
        <div class="col-12">
            <div class="glass-card card shadow">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                    <h6 class="m-0 font-weight-bold text-primary">已安装的包</h6>
                    <div class="d-flex align-items-center">
                        <div class="form-check form-switch me-3">
                            <input class="form-check-input" type="checkbox" id="showCorePackages" checked>
                            <label class="form-check-label" for="showCorePackages">
                                <small class="text-muted">显示核心包</small>
                            </label>
                        </div>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="showOnlyUserPackages">
                            <label class="form-check-label" for="showOnlyUserPackages">
                                <small class="text-muted">仅显示用户包</small>
                            </label>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" id="packagesTable">
                            <thead>
                                <tr>
                                    <th>包名</th>
                                    <th>版本</th>
                                    <th>描述</th>
                                    <th>位置</th>
                                    <th>类型</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for package in installed_packages %}
                                <tr class="package-row {% if package.is_core %}core-package{% else %}user-package{% endif %}" 
                                    data-package-type="{% if package.is_core %}core{% else %}user{% endif %}">
                                    <td>
                                        <strong>{{ package.name }}</strong>
                                        {% if package.is_core %}
                                            <i class="fas fa-shield-alt text-warning ms-1" title="核心系统包"></i>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <span class="badge badge-secondary">{{ package.version }}</span>
                                    </td>
                                    <td>
                                        <small class="text-muted">{{ package.summary or '无描述' }}</small>
                                    </td>
                                    <td>
                                        <small class="text-muted">{{ package.location }}</small>
                                    </td>
                                    <td>
                                        {% if package.is_core %}
                                            <span class="badge badge-warning">
                                                <i class="fas fa-shield-alt me-1"></i>核心包
                                            </span>
                                        {% else %}
                                            <span class="badge badge-success">
                                                <i class="fas fa-user me-1"></i>用户包
                                            </span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if package.is_core %}
                                            <div class="compact-btn-group">
                                                <button class="btn btn-info btn-sm" onclick="showCorePackageInfo('{{ package.name }}', '{{ package.core_description }}')" title="查看信息">
                                                    <i class="fas fa-info-circle"></i>
                                                </button>
                                                <button class="btn btn-warning btn-sm" onclick="showCorePackageWarning('{{ package.name }}')" title="升级警告">
                                                    <i class="fas fa-exclamation-triangle"></i>
                                                </button>
                                            </div>
                                        {% else %}
                                            <div class="compact-btn-group">
                                                <button class="btn btn-warning btn-sm" onclick="upgradePackage('{{ package.name }}')" title="升级">
                                                    <i class="fas fa-arrow-up"></i>
                                                </button>
                                                <button class="btn btn-danger btn-sm" onclick="uninstallPackage('{{ package.name }}')" title="卸载">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 实时进度监控模态框 -->
<div class="modal fade" id="progressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false" style="z-index: 1060;">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="progressModalTitle">
                    <i class="fas fa-download mr-2"></i>包安装进度
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="closeProgressBtn" style="display: none;"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="progress-info mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div>
                                    <span class="text-muted">正在安装：</span>
                                    <span id="progressPackageName" class="fw-bold text-primary fs-5"></span>
                                </div>
                                <span id="progressElapsedTime" class="text-muted"></span>
                            </div>
                            <div class="progress" style="height: 25px;">
                                <div class="progress-bar progress-bar-striped progress-bar-animated" id="progressBar" role="progressbar" style="width: 0%">
                                    <span id="progressBarText" class="fw-bold">0%</span>
                                </div>
                            </div>
                        </div>
                        <div class="progress-messages">
                            <h6>实时日志：</h6>
                            <div id="progressMessages" class="bg-dark text-light p-3 rounded" style="height: 400px; overflow-y: auto; font-family: monospace; font-size: 12px;">
                                <div class="text-muted">等待开始...</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="progress-stats">
                            <h6>统计信息：</h6>
                            <div class="card">
                                <div class="card-body">
                                    <div class="mb-2">
                                        <small class="text-muted">操作类型：</small>
                                        <div id="progressOperation" class="fw-bold"></div>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">状态：</small>
                                        <div id="progressStatus" class="fw-bold"></div>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">消息数量：</small>
                                        <div id="progressMessageCount" class="fw-bold">0</div>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">运行时间：</small>
                                        <div id="progressDuration" class="fw-bold">0秒</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="clearProgressBtn">清除进度</button>
                <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="closeProgressModalBtn" style="display: none;">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 操作结果模态框 -->
<div class="modal fade" id="resultModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="resultModalTitle">操作结果</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="resultContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 确认卸载模态框 -->
<div class="modal fade" id="confirmModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认操作</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="confirmMessage"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmButton">确认</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 全局变量
let progressPollingInterval = null;
let progressStartTime = null;
let clientStartTime = null;

// 安装包
$('#installForm').on('submit', function(e) {
    e.preventDefault();
    console.log('安装表单提交事件触发');
    
    const packageName = $('#installPackageName').val().trim();
    const version = $('#installVersion').val().trim();
    const mirrorSource = $('#mirrorSource').val();
    
    console.log('包名:', packageName);
    console.log('版本:', version);
    console.log('镜像源:', mirrorSource);
    
    if (!packageName) {
        showAlert('请输入包名', 'error');
        return;
    }
    
    // 显示加载状态
    const submitBtn = $(this).find('button[type="submit"]');
    const originalText = submitBtn.html();
    submitBtn.html('<i class="fas fa-spinner fa-spin mr-1"></i>安装中...').prop('disabled', true);
    
    // 显示进度监控模态框
    showProgressModal(packageName, 'install');
    
    // 先设置镜像源
    $.ajax({
        url: '{{ url_for("set_mirror") }}',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            mirror_name: mirrorSource
        }),
        success: function(mirrorResponse) {
            if (mirrorResponse.success) {
                console.log('镜像源设置成功:', mirrorResponse.message);
                
                // 更新进度信息
                $('#progressMessages').html('<div class="text-success">[INFO] 镜像源设置成功: ' + mirrorResponse.message + '</div>');
                
                // 然后安装包
                $.ajax({
                    url: '{{ url_for("install_package") }}',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        package_name: packageName,
                        version: version || null
                    }),
                    success: function(response) {
                        if (response.success) {
                            // 安装任务已启动，继续轮询进度
                            console.log('安装任务已启动:', response.message);
                            // 不停止进度轮询，让updateProgress函数处理完成状态
                            $('#installForm')[0].reset();
                        } else {
                            // 启动失败，停止轮询并显示错误
                            stopProgressPolling();
                            showResult('安装失败', response.message, response.error || '', response.progress || []);
                        }
                    },
                    error: function() {
                        stopProgressPolling();
                        hideProgressModal();
                        showAlert('网络错误，请重试', 'error');
                    },
                    complete: function() {
                        submitBtn.html(originalText).prop('disabled', false);
                    }
                });
            } else {
                stopProgressPolling();
                hideProgressModal();
                showAlert('设置镜像源失败: ' + mirrorResponse.message, 'error');
                submitBtn.html(originalText).prop('disabled', false);
            }
        },
        error: function() {
            stopProgressPolling();
            hideProgressModal();
            showAlert('设置镜像源失败，请重试', 'error');
            submitBtn.html(originalText).prop('disabled', false);
        }
    });
});



// 升级包
function upgradePackage(packageName, forceCore = false) {
    // 检查是否为核心包
    const corePackages = ['flask', 'sqlalchemy', 'alembic', 'requests', 'certifi', 'urllib3', 'charset-normalizer', 'idna', 'six', 'typing-extensions', 'markupsafe', 'jinja2', 'werkzeug', 'click', 'itsdangerous', 'blinker', 'greenlet', 'mako', 'apscheduler', 'python-dateutil', 'python-dotenv', 'pytz', 'setuptools', 'pip', 'wheel', 'pkg-resources', 'cryptography', 'bcrypt', 'pycryptodome', 'flask-sqlalchemy', 'flask-migrate', 'flask-login', 'flask-wtf', 'flask-cors'];
    
    if (corePackages.includes(packageName.toLowerCase())) {
        // 核心包不允许升级
        showAlert(`无法升级核心包: ${packageName}。这是系统运行必需的核心包，不允许升级。`, 'error');
        return;
    }
    
    showConfirm(`确定要升级包 "${packageName}" 吗？`, function() {
        // 显示进度监控模态框
        showProgressModal(packageName, 'upgrade');
        
        $.ajax({
            url: '{{ url_for("upgrade_package") }}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                package_name: packageName
            }),
            success: function(response) {
                if (response.success) {
                    // 升级任务已启动，继续轮询进度
                    console.log('升级任务已启动:', response.message);
                    // 不停止进度轮询，让updateProgress函数处理完成状态
                } else {
                    // 启动失败，停止轮询并显示错误
                    stopProgressPolling();
                    showResult('升级失败', response.message, response.error || '', response.progress || []);
                }
            },
            error: function() {
                stopProgressPolling();
                hideProgressModal();
                showAlert('网络错误，请重试', 'error');
            }
        });
    });
}

// 卸载包
function uninstallPackage(packageName) {
    // 检查是否为核心包
    const corePackages = ['flask', 'sqlalchemy', 'alembic', 'requests', 'certifi', 'urllib3', 'charset-normalizer', 'idna', 'six', 'typing-extensions', 'markupsafe', 'jinja2', 'werkzeug', 'click', 'itsdangerous', 'blinker', 'greenlet', 'mako', 'apscheduler', 'python-dateutil', 'python-dotenv', 'pytz', 'setuptools', 'pip', 'wheel', 'pkg-resources', 'cryptography', 'bcrypt', 'pycryptodome', 'flask-sqlalchemy', 'flask-migrate', 'flask-login', 'flask-wtf', 'flask-cors'];
    
    if (corePackages.includes(packageName.toLowerCase())) {
        showAlert(`无法卸载核心包: ${packageName}。这是系统运行必需的核心包，卸载可能导致系统无法正常工作。`, 'error');
        return;
    }
    
    showConfirm(`确定要卸载包 "${packageName}" 吗？此操作不可逆！`, function() {
        $.ajax({
            url: '{{ url_for("uninstall_package") }}',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                package_name: packageName
            }),
            success: function(response) {
                if (response.success) {
                    showResult('卸载成功', response.message, response.output || '');
                    setTimeout(refreshPackages, 1000);
                } else {
                    showResult('卸载失败', response.message, response.error || '');
                }
            },
            error: function() {
                showAlert('网络错误，请重试', 'error');
            }
        });
    });
}

// 刷新包列表
function refreshPackages() {
    // 显示加载指示器
    $('#packagesTable tbody').html('<tr><td colspan="6" class="text-center"><i class="fas fa-spinner fa-spin mr-2"></i>正在加载包列表...</td></tr>');
    
    $.ajax({
        url: '{{ url_for("refresh_packages") }}',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                // 更新统计数据
                updatePackageStats(response.total_packages, response.user_packages_count, response.core_packages_count);
                
                // 保存包数据到表格元素，以便过滤功能使用
                $('#packagesTable').data('packages', response.installed_packages);
                $('#packagesTable').data('dynamic-loaded', true);
                
                // 更新包列表
                updatePackageTable(response.installed_packages);
                
                // 显示成功消息
                showAlert('包列表已刷新', 'success');
            } else {
                showAlert(response.message || '刷新失败', 'error');
            }
        },
        error: function() {
            showAlert('刷新失败，请重试', 'error');
        }
    });
}

// 更新统计数据
function updatePackageStats(total, user, core) {
    // 更新统计卡片
    $('.total-packages').text(total);
    $('.user-packages').text(user);
    $('.core-packages').text(core);
}

// 更新包列表表格
function updatePackageTable(packages) {
    const tbody = $('#packagesTable tbody');
    tbody.empty();
    
    if (packages.length === 0) {
        tbody.html('<tr><td colspan="6" class="text-center">没有找到已安装的包</td></tr>');
        return;
    }
    
    // 按名称排序
    packages.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
    
    // 获取过滤设置
    const showCorePackages = $('#showCorePackages').is(':checked');
    const showOnlyUserPackages = $('#showOnlyUserPackages').is(':checked');
    
    console.log('过滤设置:', { showCorePackages, showOnlyUserPackages });
    console.log('包总数:', packages.length);
    console.log('核心包数量:', packages.filter(p => p.is_core).length);
    
    // 添加每个包的行
    let displayedCount = 0;
    packages.forEach(function(pkg) {
        // 根据过滤设置决定是否显示
        if ((pkg.is_core && !showCorePackages) || (showOnlyUserPackages && pkg.is_core)) {
            return; // 跳过不符合过滤条件的包
        }
        displayedCount++;
        
        const row = $('<tr></tr>');
        row.addClass(pkg.is_core ? 'core-package' : 'user-package');
        row.attr('data-package-type', pkg.is_core ? 'core' : 'user');
        
        // 添加包名列（带核心标记）
        let nameCell = $('<td></td>');
        if (pkg.is_core) {
            nameCell.html(`<strong>${pkg.name}</strong> <i class="fas fa-shield-alt text-warning ms-1" title="核心系统包"></i>`);
        } else {
            nameCell.html(`<strong>${pkg.name}</strong>`);
        }
        row.append(nameCell);
        
        // 添加版本列
        row.append(`<td><span class="badge badge-secondary">${pkg.version || '-'}</span></td>`);
        
        // 添加描述列（优先使用核心描述）
        let description = pkg.core_description || pkg.summary || '-';
        row.append(`<td><small class="text-muted">${description}</small></td>`);
        
        // 添加位置列
        row.append(`<td><small class="text-muted">${pkg.location || '-'}</small></td>`);
        
        // 添加类型列
        let typeCell = $('<td></td>');
        if (pkg.is_core) {
            typeCell.html('<span class="badge badge-warning"><i class="fas fa-shield-alt me-1"></i>核心包</span>');
        } else {
            typeCell.html('<span class="badge badge-success"><i class="fas fa-user me-1"></i>用户包</span>');
        }
        row.append(typeCell);
        
        // 添加操作列
        let actionsCell = $('<td></td>');
        let actionBtns = $('<div class="compact-btn-group"></div>');
        
        if (pkg.is_core) {
            // 核心包的操作按钮 - 只显示信息按钮
            actionBtns.append(`<button class="btn btn-info btn-sm" onclick="showCorePackageInfo('${pkg.name}', '${pkg.core_description}')" title="查看信息"><i class="fas fa-info-circle"></i></button>`);
            actionBtns.append(`<button class="btn btn-secondary btn-sm" disabled title="核心包不允许操作"><i class="fas fa-lock"></i></button>`);
        } else {
            // 用户包的操作按钮
            actionBtns.append(`<button class="btn btn-warning btn-sm" onclick="upgradePackage('${pkg.name}')" title="升级"><i class="fas fa-arrow-up"></i></button>`);
            actionBtns.append(`<button class="btn btn-danger btn-sm" onclick="uninstallPackage('${pkg.name}')" title="卸载"><i class="fas fa-trash"></i></button>`);
        }
        
        actionsCell.append(actionBtns);
        row.append(actionsCell);
        
        tbody.append(row);
    });
    
    // 如果没有显示任何包，显示提示信息
    if (tbody.children().length === 0) {
        tbody.html('<tr><td colspan="6" class="text-center">没有符合过滤条件的包</td></tr>');
    }
    
    console.log('实际显示的包数量:', displayedCount);
    console.log('表格中的行数:', tbody.children().length);
}

// 加载包列表（不重新加载页面）
function loadPackages() {
    // 这里可以添加AJAX加载包列表的逻辑
    // 暂时不做任何操作，因为包列表是通过服务器端渲染的
    console.log('包列表已加载');
}

// 显示核心包信息
function showCorePackageInfo(packageName, description) {
    // 创建模态框
    const modal = $(`
        <div class="modal fade" id="corePackageInfoModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-shield-alt text-warning me-2"></i>核心包信息</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <i class="fas fa-info-circle me-2"></i>核心包是系统正常运行所必需的，请勿随意修改或卸载。
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">包名称</label>
                            <p>${packageName}</p>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">包描述</label>
                            <p>${description || '无描述'}</p>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `);
    
    // 添加到页面并显示
    $('body').append(modal);
    modal.modal('show');
    
    // 模态框关闭后移除
    modal.on('hidden.bs.modal', function() {
        modal.remove();
    });
}

// 显示核心包信息警告
function showCorePackageWarning(packageName) {
    // 创建模态框
    const modal = $(`
        <div class="modal fade" id="corePackageWarningModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header bg-warning text-white">
                        <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>核心包警告</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i><strong>警告：</strong>系统核心包 <strong>${packageName}</strong> 不允许升级或卸载。
                        </div>
                        <p>核心包是系统正常运行所必需的，为了保证系统稳定性，不允许对核心包进行升级或卸载操作。</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">我知道了</button>
                    </div>
                </div>
            </div>
        </div>
    `);
    
    // 添加到页面并显示
    $('body').append(modal);
    modal.modal('show');
    
    // 模态框关闭后移除
    modal.on('hidden.bs.modal', function() {
        modal.remove();
    });
}

// 显示操作结果
function showResult(title, message, details, progress) {
    console.log('显示结果模态框:', title, message);
    
    // 先关闭进度模态框
    hideProgressModal();
    
    // 等待一小段时间确保进度模态框完全关闭
    setTimeout(function() {
        $('#resultModalTitle').text(title);
        let content = `<div class="alert alert-${title.includes('成功') ? 'success' : 'danger'}">${message}</div>`;
        
        // 显示进度信息
        if (progress && progress.length > 0) {
            content += `<h6>安装进度：</h6><div class="bg-light p-3 rounded" style="max-height: 200px; overflow-y: auto;">`;
            progress.forEach(function(progressItem) {
                const level = progressItem.includes('[ERROR]') ? 'danger' : 
                             progressItem.includes('[WARNING]') ? 'warning' : 'info';
                content += `<div class="text-${level} small mb-1">${progressItem}</div>`;
            });
            content += `</div>`;
        }
        
        if (details) {
            content += `<h6>详细信息：</h6><pre class="bg-light p-3 rounded"><code>${details}</code></pre>`;
        }
        $('#resultContent').html(content);
        
        // 显示结果模态框 - 统一使用Bootstrap 5 API
        const resultModalElement = document.getElementById('resultModal');
        if (resultModalElement) {
            const modal = new bootstrap.Modal(resultModalElement);
            modal.show();
            console.log('结果模态框已显示');
        }
    }, 400);
}

// 显示确认对话框
function showConfirm(message, callback) {
    $('#confirmMessage').text(message);
    $('#confirmButton').off('click').on('click', function() {
        // 统一使用Bootstrap 5 API
        const modalElement = document.getElementById('confirmModal');
        if (modalElement) {
            const modal = bootstrap.Modal.getInstance(modalElement);
            if (modal) {
                modal.hide();
            }
        }
        callback();
    });
    
    // 统一使用Bootstrap 5 API
    const modalElement = document.getElementById('confirmModal');
    if (modalElement) {
        const modal = new bootstrap.Modal(modalElement);
        modal.show();
    }
}

// 调试函数
function debugInstall() {
    console.log('安装表单提交事件触发');
    const packageName = $('#installPackageName').val().trim();
    const version = $('#installVersion').val().trim();
    console.log('包名:', packageName);
    console.log('版本:', version);
}

// 显示提示信息
function showAlert(message, type) {
    const alertClass = type === 'error' ? 'danger' : type === 'warning' ? 'warning' : 'info';
    const alertHtml = `
        <div class="alert alert-${alertClass} alert-dismissible fade show" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    $('.container-fluid').prepend(alertHtml);
    
    // 3秒后自动消失
    setTimeout(function() {
        // 统一使用Bootstrap 5 API
        const alertElement = document.querySelector('.alert');
        if (alertElement) {
            const alert = new bootstrap.Alert(alertElement);
            alert.close();
        }
    }, 3000);
}

// 加载当前镜像源
function loadCurrentMirror() {
    $.ajax({
        url: '{{ url_for("get_mirrors") }}',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const currentMirror = response.current_mirror;
                const mirrors = response.mirrors;
                
                // 找到对应的镜像源名称
                for (const [name, url] of Object.entries(mirrors)) {
                    if (url === currentMirror) {
                        $('#mirrorSource').val(name);
                        break;
                    }
                }
            }
        },
        error: function() {
            console.log('获取镜像源信息失败');
        }
    });
}

// 显示进度监控模态框
function showProgressModal(packageName, operation) {
    console.log('显示进度模态框:', packageName, operation);
    
    // 记录客户端开始时间
    clientStartTime = Date.now();
    
    // 先确保关闭所有其他模态框
    $('.modal').modal('hide');
    
    // 等待其他模态框完全关闭
    setTimeout(function() {
        // 重置进度信息
        $('#progressPackageName').text(packageName || '未知包');
        $('#progressOperation').text(operation === 'install' ? '安装' : '升级');
        $('#progressStatus').text('运行中');
        $('#progressMessageCount').text('0');
        $('#progressDuration').text('0秒');
        $('#progressMessages').html('<div class="text-muted">正在启动安装...</div>');
        $('#progressBar').css('width', '0%').removeClass('bg-success bg-danger').addClass('progress-bar-animated');
        $('#progressBarText').text('0%');
        
        // 隐藏关闭按钮
        $('#closeProgressBtn').hide();
        $('#closeProgressModalBtn').hide();
        
        // 显示模态框 - 统一使用Bootstrap 5 API
        const modalElement = document.getElementById('progressModal');
        if (modalElement) {
            // 确保模态框有正确的z-index
            modalElement.style.zIndex = '1060';
            const modal = new bootstrap.Modal(modalElement, {
                backdrop: 'static',
                keyboard: false
            });
            modal.show();
            console.log('进度模态框已显示');
        }
        
        // 开始轮询进度
        startProgressPolling();
    }, 300);
}

// 隐藏进度监控模态框
function hideProgressModal() {
    console.log('尝试关闭进度模态框');
    
    // 先停止进度轮询
    stopProgressPolling();
    
    // 统一使用Bootstrap 5 API
    const modalElement = document.getElementById('progressModal');
    if (modalElement) {
        const modal = bootstrap.Modal.getInstance(modalElement);
        if (modal) {
            console.log('使用Bootstrap 5关闭模态框');
            modal.hide();
        } else {
            console.log('Bootstrap模态框实例不存在，使用jQuery关闭');
            $('#progressModal').modal('hide');
        }
    }
    
    // 强制清理模态框状态
    setTimeout(function() {
        const modalElement = document.getElementById('progressModal');
        if (modalElement) {
            modalElement.classList.remove('show');
            modalElement.style.display = 'none';
            modalElement.setAttribute('aria-hidden', 'true');
            modalElement.removeAttribute('aria-modal');
        }
        document.body.classList.remove('modal-open');
        const backdrops = document.querySelectorAll('.modal-backdrop');
        backdrops.forEach(backdrop => backdrop.remove());
        console.log('进度模态框已完全关闭');
    }, 200);
}

// 开始进度轮询
function startProgressPolling() {
    progressStartTime = Date.now();
    
    // 立即获取一次进度
    updateProgress();
    
    // 每2秒轮询一次
    progressPollingInterval = setInterval(updateProgress, 2000);
}

// 停止进度轮询
function stopProgressPolling() {
    if (progressPollingInterval) {
        clearInterval(progressPollingInterval);
        progressPollingInterval = null;
    }
}

// 更新进度信息
function updateProgress() {
    $.ajax({
        url: '{{ url_for("get_progress") }}',
        method: 'GET',
        success: function(response) {
            if (response.success && response.progress) {
                const progress = response.progress;
                
                // 更新基本信息
                if (progress.current_package) {
                    $('#progressPackageName').text(progress.current_package);
                }
                $('#progressOperation').text(progress.operation === 'install' ? '安装' : 
                                              progress.operation === 'upgrade' ? '升级' : 
                                              progress.operation === 'uninstall' ? '卸载' : '未知');
                $('#progressStatus').text(progress.status === 'running' ? '运行中' : 
                                          progress.status === 'success' ? '成功' : 
                                          progress.status === 'failed' ? '失败' : 
                                          progress.status === 'completed' ? '完成' : '空闲');
                $('#progressMessageCount').text(progress.progress_messages ? progress.progress_messages.length : 0);
                
                // 更新运行时间 - 优先使用服务器时间，备用客户端时间
                let elapsed = 0;
                if (progress.elapsed_time) {
                    elapsed = Math.floor(progress.elapsed_time);
                } else if (clientStartTime) {
                    elapsed = Math.floor((Date.now() - clientStartTime) / 1000);
                }
                
                if (elapsed > 0) {
                    const minutes = Math.floor(elapsed / 60);
                    const seconds = elapsed % 60;
                    const timeText = minutes > 0 ? `${minutes}分${seconds}秒` : `${seconds}秒`;
                    $('#progressDuration').text(timeText);
                    $('#progressElapsedTime').text(`已运行 ${timeText}`);
                } else {
                    $('#progressDuration').text('0秒');
                }
                
                // 更新进度条
                if (progress.status === 'running') {
                    // 使用服务器返回的进度值
                    const progressPercent = progress.progress || 0;
                    $('#progressBar').css('width', progressPercent + '%').addClass('progress-bar-animated');
                    $('#progressBarText').text(progressPercent + '%');
                } else if (progress.status === 'success' || progress.status === 'completed') {
                    $('#progressBar').css('width', '100%').removeClass('progress-bar-animated').addClass('bg-success');
                    $('#progressBarText').text('100% - 完成');
                } else if (progress.status === 'failed') {
                    $('#progressBar').css('width', '100%').removeClass('progress-bar-animated').addClass('bg-danger');
                    $('#progressBarText').text('100% - 失败');
                }
                
                // 更新消息列表
                if (progress.progress_messages && progress.progress_messages.length > 0) {
                    let messagesHtml = '';
                    progress.progress_messages.forEach(function(msg) {
                        // 处理时间戳 - 支持多种格式
                        let timestamp = '';
                        if (msg.timestamp) {
                            if (typeof msg.timestamp === 'number') {
                                timestamp = new Date(msg.timestamp * 1000).toLocaleTimeString();
                            } else {
                                timestamp = new Date(msg.timestamp).toLocaleTimeString();
                            }
                        } else {
                            timestamp = new Date().toLocaleTimeString();
                        }
                        
                        // 处理消息级别
                        const levelClass = msg.level === 'error' ? 'text-danger' : 
                                         msg.level === 'warning' ? 'text-warning' : 
                                         msg.level === 'success' ? 'text-success' : 'text-info';
                        
                        // 处理消息内容 - 确保显示完整信息
                        let message = msg.message || msg.text || msg.content || '未知消息';
                        
                        // 如果消息很长，保持原样显示（不截断）
                        messagesHtml += `<div class="${levelClass}" style="word-wrap: break-word; white-space: pre-wrap;">[${timestamp}] ${message}</div>`;
                    });
                    $('#progressMessages').html(messagesHtml);
                    
                    // 滚动到底部
                    const messagesDiv = document.getElementById('progressMessages');
                    if (messagesDiv) {
                        messagesDiv.scrollTop = messagesDiv.scrollHeight;
                    }
                } else if (progress.status === 'success' || progress.status === 'completed') {
                    // 如果没有详细消息但操作成功，显示基本成功信息
                    const timestamp = new Date().toLocaleTimeString();
                    $('#progressMessages').html(`<div class="text-success">[${timestamp}] 操作执行成功</div>`);
                } else if (progress.status === 'failed') {
                    // 如果没有详细消息但操作失败，显示基本失败信息
                    const timestamp = new Date().toLocaleTimeString();
                    $('#progressMessages').html(`<div class="text-danger">[${timestamp}] 操作执行失败</div>`);
                }
                
                // 如果操作完成，显示关闭按钮并停止轮询
                if (progress.status === 'success' || progress.status === 'completed' || progress.status === 'failed') {
                    $('#closeProgressBtn').show();
                    $('#closeProgressModalBtn').show();
                    $('#progressBar').removeClass('progress-bar-animated');
                    
                    // 停止进度轮询
                    stopProgressPolling();
                    
                    // 如果是成功完成的安装或升级，刷新包列表
                    if ((progress.status === 'success' || progress.status === 'completed') && 
                        (progress.operation === 'install' || progress.operation === 'upgrade')) {
                        console.log('操作成功完成，刷新包列表');
                        setTimeout(refreshPackages, 1000);
                    }
                }
            } else {
                // 如果没有进度信息，显示默认状态
                $('#progressStatus').text('等待中...');
                $('#progressDuration').text('0秒');
            }
        },
        error: function() {
            console.log('获取进度信息失败');
            $('#progressStatus').text('连接失败');
        }
    });
}

// 清除进度信息
$('#clearProgressBtn').on('click', function() {
    $.ajax({
        url: '{{ url_for("clear_progress") }}',
        method: 'POST',
        success: function(response) {
            if (response.success) {
                $('#progressMessages').html('<div class="text-muted">进度信息已清除</div>');
                $('#progressStatus').text('空闲');
                $('#progressMessageCount').text('0');
                $('#progressDuration').text('0秒');
                $('#progressBar').css('width', '0%').removeClass('bg-success bg-danger progress-bar-animated');
            }
        }
    });
});

// 后台安装功能已移除

// 全局变量，防止重复显示通知
let notificationShown = false;

// 页面加载完成后执行
$(document).ready(function() {
    // 检查是否有运行中的任务
    checkRunningTasks();
    
    // 初始化过滤开关状态 - 默认显示所有包
    $('#showCorePackages').prop('checked', true);
    $('#showOnlyUserPackages').prop('checked', false);
    
    // 初始化核心包显示控制
    initCorePackageDisplay();
    
    // 获取当前镜像源
    loadCurrentMirror();
    
    // 刷新包列表（动态加载）- 确保在初始化过滤器后执行
    setTimeout(refreshPackages, 100);
});

// 初始化核心包显示控制
function initCorePackageDisplay() {
    console.log('初始化核心包显示控制');
    // 默认显示所有包
    $('.core-package').show();
    
    // 显示核心包复选框事件
    $('#showCorePackages').on('change', function() {
        const showCore = $(this).is(':checked');
        const showOnlyUser = $('#showOnlyUserPackages').is(':checked');
        
        console.log('显示核心包复选框变更:', { showCore, showOnlyUser });
        
        // 如果是动态加载的包列表，使用 updatePackageTable 重新过滤
        if ($('#packagesTable').data('dynamic-loaded')) {
            // 获取当前已加载的包数据
            const packages = $('#packagesTable').data('packages') || [];
            console.log('重新过滤包列表，包数量:', packages.length);
            // 更新表格显示
            updatePackageTable(packages);
        } else {
            // 静态渲染的包列表，使用 CSS 显示/隐藏
            if (showCore) {
                $('.core-package').show();
                console.log('显示核心包 (CSS)');
            } else {
                $('.core-package').hide();
                console.log('隐藏核心包 (CSS)');
            }
        }
        
        // 更新仅显示用户包的复选框状态
        if (showCore && showOnlyUser) {
            $('#showOnlyUserPackages').prop('checked', false);
            console.log('自动取消仅显示用户包复选框');
        }
    });
    
    // 仅显示用户包复选框事件
    $('#showOnlyUserPackages').on('change', function() {
        const showOnlyUser = $(this).is(':checked');
        const showCore = $('#showCorePackages').is(':checked');
        
        console.log('仅显示用户包复选框变更:', { showOnlyUser, showCore });
        
        // 如果是动态加载的包列表，使用 updatePackageTable 重新过滤
        if ($('#packagesTable').data('dynamic-loaded')) {
            // 获取当前已加载的包数据
            const packages = $('#packagesTable').data('packages') || [];
            console.log('重新过滤包列表，包数量:', packages.length);
            // 更新表格显示
            updatePackageTable(packages);
        } else {
            // 静态渲染的包列表，使用 CSS 显示/隐藏
            if (showOnlyUser) {
                $('.core-package').hide();
                $('#showCorePackages').prop('checked', false);
                console.log('仅显示用户包，隐藏核心包 (CSS)');
            } else if (!showCore) {
                // 如果两个都不选中，显示所有包
                console.log('两个复选框都未选中，显示所有包');
                $('.core-package').show();
            }
        }
    });
}

// 显示核心包信息
function showCorePackageInfo(packageName, description) {
    showResultModal(
        `核心包信息 - ${packageName}`,
        `
        <div class="alert alert-info">
            <h6><i class="fas fa-shield-alt text-warning me-2"></i>核心系统包</h6>
            <p class="mb-2"><strong>包名：</strong>${packageName}</p>
            <p class="mb-2"><strong>描述：</strong>${description || '核心系统包 - 系统运行必需'}</p>
            <p class="mb-0"><strong>状态：</strong><span class="badge badge-warning">受保护</span></p>
        </div>
        <div class="alert alert-warning">
            <h6><i class="fas fa-exclamation-triangle text-warning me-2"></i>安全提醒</h6>
            <p class="mb-0">此包为系统核心组件，不建议进行卸载或降级操作，以免影响系统稳定性。</p>
        </div>
        `
    );
}

// 显示核心包升级警告
function showCorePackageWarning(packageName) {
    showResultModal(
        `核心包升级警告 - ${packageName}`,
        `
        <div class="alert alert-danger">
            <h6><i class="fas fa-exclamation-triangle text-danger me-2"></i>升级警告</h6>
            <p class="mb-2">您正在尝试升级核心系统包 <strong>${packageName}</strong></p>
            <p class="mb-2">核心包的升级可能会：</p>
            <ul class="mb-3">
                <li>影响系统稳定性</li>
                <li>导致功能异常</li>
                <li>破坏依赖关系</li>
                <li>需要重启服务</li>
            </ul>
            <p class="mb-0"><strong>建议：</strong>仅在必要时且充分测试后进行升级。</p>
        </div>
        <div class="d-flex justify-content-between">
            <button class="btn btn-secondary" onclick="$('#resultModal').modal('hide')">取消</button>
            <button class="btn btn-warning" onclick="confirmUpgradeCorePackage('${packageName}')">
                <i class="fas fa-arrow-up me-1"></i>确认升级
            </button>
        </div>
        `
    );
}

// 确认升级核心包
function confirmUpgradeCorePackage(packageName) {
    $('#resultModal').modal('hide');
    
    showConfirm(
        `确定要升级核心包 "${packageName}" 吗？<br><br>
        <small class="text-warning">
            <i class="fas fa-exclamation-triangle me-1"></i>
            此操作可能会影响系统稳定性，建议在维护窗口期间进行。
        </small>`,
        function() {
            // 执行升级操作，传递 forceCore=true 参数
            upgradePackage(packageName, true);
        }
    );
}

// 检查运行中的任务
function checkRunningTasks() {
    // 如果已经显示过通知，就不再检查
    if (notificationShown) {
        return;
    }
    
    $.ajax({
        url: '{{ url_for("check_running_tasks") }}',
        method: 'GET',
        success: function(response) {
            if (response.success && response.has_running_tasks) {
                // 显示后台任务提示，但不强制跳转
                console.log('检测到后台任务正在运行');
                
                // 只显示运行中的任务数量，不包括未完成的任务
                const runningTasksCount = response.running_tasks_count || 0;
                
                if (runningTasksCount > 0) {
                    showBackgroundTaskNotification(runningTasksCount);
                }
            }
        },
        error: function() {
            console.log('检查运行任务失败');
        }
    });
}

// 显示后台任务通知
function showBackgroundTaskNotification(taskCount) {
    // 多重检查，确保不会重复显示
    if (notificationShown || $('#backgroundTaskNotification').length > 0) {
        console.log('通知已存在，跳过显示');
        return;
    }
    
    // 设置标志，防止重复显示
    notificationShown = true;
    
    // 创建通知元素
    const notification = $(`
        <div class="alert alert-info alert-dismissible fade show" role="alert" id="backgroundTaskNotification">
            <i class="fas fa-server mr-2"></i>
            <strong>后台任务提醒：</strong>您有 ${taskCount} 个后台安装任务正在运行。
            <a href="{{ url_for('package_progress') }}" class="alert-link">查看进度</a>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `);
    
    // 插入到页面顶部
    $('.container-fluid').prepend(notification);
    
    // 5秒后自动隐藏
    setTimeout(function() {
        $('#backgroundTaskNotification').fadeOut(function() {
            // 隐藏后移除元素并重置标志
            $(this).remove();
            notificationShown = false;
        });
    }, 5000);
    
    // 手动关闭按钮事件
    notification.find('.btn-close').on('click', function() {
        notificationShown = false;
    });
}
</script>
{% endblock %}